import io
import socket
import struct
import time
import cv2
import numpy as np

HOST = '192.168.228.198'
class pic_put():
    def __init__(self):
        self.h = HOST
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_socket.connect((self.h, 8000))  #
        self.connection = self.client_socket.makefile('wb')
        self.stream = io.BytesIO()

    def upload(self, frame):
        img_encode = cv2.imencode('.jpg', frame)[1]
        data_encode = np.array(img_encode)
        self.stream.write(data_encode)
        self.connection.write(struct.pack('<L', self.stream.tell()))
        self.connection.flush()
        self.stream.seek(0)
        self.connection.write(self.stream.read())
        self.stream.seek(0)
        self.stream.truncate()
        self.connection.write(struct.pack('<L', 0))

    def close(self):
        msg = 'exit'
        self.client_socket.send(msg.encode('utf-8'))
        self.connection.close()
        self.client_socket.close()



cap = cv2.VideoCapture(0)
pic = pic_put()

while True:
    value,frame =cap.read()
    pic.upload(frame)


